package com.limiter;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 漏桶限流
 */
public class LeakBucketLimiter {
    //桶的大小
    private static long capacity=10;
    //桶的流速
    private static long rate=2;
    //开始时间
    private static long startTime=System.currentTimeMillis();
    //桶剩余的水量
    private static AtomicLong water = new AtomicLong();

    private synchronized static boolean tryAcquire(){
        //如果桶的剩余量0 直接方行
        if(water.get()==0){
            startTime = System.currentTimeMillis();
            water.set(1);
            return true;
        }
        //计算从当前时间到开始时间流出的水，和桶中剩余的水
        //桶中剩余的水
        water.set(water.get() - (System.currentTimeMillis() - startTime)/100*rate);
        //防止小于0的情况出现
        water.set(Math.max(0,water.get()));
        //设置新的时间
        startTime+=(System.currentTimeMillis()-startTime)/1000*1000;
        if(water.get()<capacity){
            water.incrementAndGet();
            return true;
        }else {
            return false;
        }
    }
}
